import { useEffect, useState } from 'react'
import './index.less'
import { App } from 'antd'

/**
 * @param tabClick tab 点击事件 , 会返回当前点击的名称
 * @param tabList tab列表
 * @returns {JSX.Element}
 * @constructor
 */

const CardTab = ({ tabClick, tabList, isPrompt = true }) => {
  const [tabActive, setTabActive] = useState(null)
  const [tabIndex, setTabIndex] = useState(0)
  const { modal } = App.useApp()

  const handleChangeTab = (item, index) => {
    if (tabActive === item.label) return

    if (isPrompt) {
      modal.confirm({
        title: '提示',
        content: '切换端口将会清空当前编辑的内容，是否继续？',
        okText: '继续',
        cancelText: '取消',
        onOk: () => {
          setTabActive(item.label)
          setTabIndex(index)
          tabClick && tabClick(item)
        },
        onCancel: () => {}
      })
    } else {
      setTabActive(item.label)
      setTabIndex(index)
      tabClick && tabClick(item)
    }
  }

  useEffect(() => {
    if (tabList && tabList.length > 0) {
      setTabActive(tabList[0].label)
      // tabClick && tabClick(tabList[0])
    }
  }, [tabList])

  return (
    <>
      {tabList && tabList.length ? (
        <div className='card_tab'>
          <div className='card_content'>
            {tabList.map((item, index) => {
              return (
                <div
                  key={item.label}
                  className={`card_tab_item ${tabActive === item.label ? 'card_tab_item_active' : ''}`}
                  onClick={() => handleChangeTab(item, index)}
                >
                  {item.name}
                </div>
              )
            })}
          </div>
          <div className='card_active' style={{ left: tabIndex * 80 + 'px' }}>
            <div className='card_item_active'></div>
          </div>
        </div>
      ) : null}
    </>
  )
}
export default CardTab
